﻿using System.Collections.Generic;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace Gateway
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication("Bearer")
                    .AddIdentityServerAuthentication("usergateway", options =>
                    {
                        options.Authority = "http://localhost:5000";        //配置Identityserver的授权地址
                        options.RequireHttpsMetadata = false;               //不需要https    
                        options.ApiName = "asp_ServerA";                    //api的name，需要和config的名称相同
                    });


            // Injection of service dependencies of Ocelot
            services.AddOcelot();

            services.AddMvc();
        }

        public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                DefaultFileNames = new List<string> { "index.html" }
            });

            app.UseStaticFiles();

            app.UseAuthentication();// 添加认证中间件 

            // Include Ocelot middleware
            await app.UseOcelot().ConfigureAwait(false);

            app.UseMvc();
        }
    }
}